package com.example.myapplicationndk.ocr;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.myapplicationndk.R;
import com.example.myapplicationndk.databinding.ActivityOcrMainBinding;
import com.example.myapplicationndk.utils.Logd;
import com.example.myapplicationndk.utils.ToastUtils;
import com.google.gson.Gson;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.jetbrains.annotations.NotNull;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class OcrMainActivity extends AppCompatActivity {

    ActivityOcrMainBinding mMainBinding;
    private int PICK_PHOTO = 101;
    private List<String> list = new ArrayList<>();
    OcrMainActivity.OnClickListener listener = new OnClickListener() {
        @Override
        public void onclick(View v, int position) {
            ToastUtils.show(list.get(position));
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull @NotNull Message msg) {
            if (msg.what == 0) {
                try {
                    SpannableString spannableString;
                    JsonRootBean json = new Gson().fromJson(msg.obj.toString(), JsonRootBean.class);
                    List<JsonRootBean.Data.Block.Line> lines = json.getData().getBlock().get(0).getLine();
                    list.clear();
                    for (JsonRootBean.Data.Block.Line line : lines) {
                        for (JsonRootBean.Data.Block.Line.Word word : line.getWord()) {
                            list.add(word.getContent());
                        }
                    }

                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(10, 5, 10, 5);
                    mMainBinding.flow.removeAllViews();
                    Logd.Logd(list.size() + "");
                    for (int i = 0; i < list.size(); i++) {
                        TextView tv = new TextView(OcrMainActivity.this);
                        tv.setTextColor(Color.parseColor("#ffffff"));
                        tv.setPadding(28, 10, 28, 10);
                        tv.setText(list.get(i));
                        tv.setMaxEms(10);
                        tv.setSingleLine();
                        tv.setBackgroundResource(R.drawable.selector_playsearch);
                        tv.setLayoutParams(layoutParams);
                        int finalI = i;
                        tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                listener.onclick(v, finalI);
                            }
                        });
                        mMainBinding.flow.addView(tv, layoutParams);
                    }

                    Logd.Logd(msg.obj.toString());
                } catch (Exception e) {
                    Logd.Logd(e.toString());
                    e.toString();
                }
            }
        }
    };

    interface OnClickListener {
        void onclick(View v, int position);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMainBinding = ActivityOcrMainBinding.inflate(getLayoutInflater());
        setContentView(mMainBinding.getRoot());

        mMainBinding.btnSelectPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(OcrMainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(OcrMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA,
                            Manifest.permission.ACCESS_FINE_LOCATION}, 101);
                } else {
                    mMainBinding.flow.removeAllViews();
                    Matisse.from(OcrMainActivity.this)
                            .choose(MimeType.ofImage(), false)
                            .countable(true)
                            .capture(true)
                            .captureStrategy(
                                    new CaptureStrategy(true, "com.zhihu.matisse.sample.fileprovider", "test"))
                            .maxSelectable(1)
                            .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .setOnSelectedListener((uriList, pathList) -> {
                                Log.e("onSelected", "onSelected: pathList=" + pathList);
                            })
                            .showSingleMediaType(true)
                            .originalEnable(true)
                            .maxOriginalSize(10)
                            .autoHideToolbarOnSingleTap(true)
                            .setOnCheckedListener(isChecked -> {
                                Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                            })
                            .forResult(PICK_PHOTO);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                List<Uri> pathList = Matisse.obtainResult(data);
                for (Uri _Uri : pathList) {
                    Glide.with(this).load(_Uri).into(mMainBinding.ivPhoto);
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(_Uri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    OcrReconginze(bitmap);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    //    @TargetApi(19)
//    private void handleImageOnKitKat(Intent data) {
//        String imagePath = null;
//        Uri uri = data.getData();
//        if (DocumentsContract.isDocumentUri(this, uri)) {
//            // 如果是document类型的Uri，则通过document id处理
//            String docId = DocumentsContract.getDocumentId(uri);
//            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
//                String id = docId.split(":")[1];
//                // 解析出数字格式的id
//                String selection = MediaStore.Images.Media._ID + "=" + id;
//                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
//            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
//                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
//                imagePath = getImagePath(contentUri, null);
//            }
//        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
//            // 如果是content类型的Uri，则使用普通方式处理
//            imagePath = getImagePath(uri, null);
//        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
//            // 如果是file类型的Uri，直接获取图片路径即可
//            imagePath = uri.getPath();
//        }
//        // 根据图片路径显示图片
//        displayImage(imagePath);
//    }
//
//    /**
//     * android 4.4以前的处理方式
//     *
//     * @param data
//     */
//    private void handleImageBeforeKitKat(Intent data) {
//        Uri uri = data.getData();
//        String imagePath = getImagePath(uri, null);
//        displayImage(imagePath);
//    }
//
//    private String getImagePath(Uri uri, String selection) {
//        String path = null;
//        // 通过Uri和selection来获取真实的图片路径
//        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
//        if (cursor != null) {
//            if (cursor.moveToFirst()) {
//                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//            }
//            cursor.close();
//        }
//        return path;
//    }
//
//    private void displayImage(String imagePath) {
//        if (imagePath != null) {
//            Logd.Logd(imagePath);
//            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//            mMainBinding.ivPhoto.setImageBitmap(bitmap);
//            OcrReconginze(imagePath);
//        } else {
//            Toast.makeText(this, "获取相册图片失败", Toast.LENGTH_SHORT).show();
//        }
//    }


    private void OcrReconginze(Bitmap bitmap) {
        Map<String, String> header = null;
        try {
            header = WebOCR.buildHttpHeader();
            String imageBase64 = Base64Utils.bitmapToBase64(bitmap);
            HttpUtil.doPost1(mHandler, WebOCR.WEBOCR_URL, header, "image=" + URLEncoder.encode(imageBase64, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            Logd.Logd(e.toString());
            e.printStackTrace();
        }
    }


}
